package net.lovesrc.allin.jobs.backup;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import net.lovesrc.allin.jobs.base.BaseJob;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author clg
 * Created at 21:25 2019/2/27
 * @since 1.1
 */
public abstract class LbcBaseJob extends BaseJob {

    Cache<String, String> cache = CacheBuilder.newBuilder()
            .maximumSize(100)
            .expireAfterWrite(30, TimeUnit.MINUTES)
            .concurrencyLevel(10)
            .recordStats()
            .build();

    protected String getEmail() {
        return "chen7242538@jfsite.site";
    }

    @Override
    protected void sendNotificationToAdmin(String subject, String text) {
        notificationService.email(getEmail(), subject, text);
    }

    @Override
    protected void sendNotificationToAdmin(Throwable e) {
        String cacheKey = e.getMessage();
        try {
            if (cache.getIfPresent(cacheKey) != null) {
                return;
            }
            notificationService.email(getEmail(), e.getMessage(), ExceptionUtils.getStackTrace(e));
        } finally {
            cache.put(cacheKey, String.valueOf(System.currentTimeMillis()));
        }
    }

    public int randSeconds() {
        return randSeconds(5 * 60);
    }

    public int randSeconds(int seconds) {
        double v = new Random().nextDouble();
        return (int) (v * seconds);
    }
}
